package cn.jiyun.config;

import cn.hutool.core.collection.CollUtil;
import cn.jiyun.properties.SocketIOProperties;
import com.corundumstudio.socketio.SocketConfig;
import com.corundumstudio.socketio.SocketIOServer;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author admin
 */
@Component
@EnableConfigurationProperties(SocketIOProperties.class)
public class SocketIOConfig {

    @Resource
    private SocketIOProperties socketIOProperties;

    /**
     * 以下配置在上面的application.properties中已经注明
     *
     * @return
     */
    @Bean
    public SocketIOServer socketIOServer() {
        SocketConfig socketConfig = new SocketConfig();
        socketConfig.setTcpNoDelay(true);
        socketConfig.setSoLinger(0);
        com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration();
        config.setSocketConfig(socketConfig);
        config.setHostname(socketIOProperties.getHost());
        config.setPort(socketIOProperties.getPort());
        config.setBossThreads(socketIOProperties.getBossCount());
        config.setWorkerThreads(socketIOProperties.getWorkCount());
        config.setAllowCustomRequests(socketIOProperties.getAllowCustomRequests());
        config.setUpgradeTimeout(socketIOProperties.getUpgradeTimeout());
        config.setPingTimeout(socketIOProperties.getPingTimeout());
        config.setPingInterval(socketIOProperties.getPingInterval());

        // 鉴权
        config.setAuthorizationListener(handshakeData -> {
            // 获取socket链接发来的token参数
            String token = handshakeData.getSingleUrlParam("token");
            // todo 如果验签通过就是true,否则false, false的话就不允许建立socket链接
//                if (StringUtils.isNotEmpty(token) && StpUtil.getLoginIdByToken(token) != null) {
//                    return true;
//                }

                return true;

//            return false;
        });
        SocketIOServer socketIOServer = new SocketIOServer(config);
        List<String> namespaceList = socketIOProperties.getNamespaceList();
        // 添加命名空间
        if (CollUtil.isNotEmpty(namespaceList)) {
            for (String namespace : namespaceList) {
                socketIOServer.addNamespace(namespace);
            }
        }
        return socketIOServer;
    }

}

